﻿using Furion.CMS.Application;
using Furion.CMS.Core;
using Furion.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Furion.CMS.Web.Core
{
    /// <summary>
    /// 缓存引导加载
    /// </summary>
    public class GlobalCacheBootLoader : ISingleton
    {
        private readonly IDistributedCache<IEnumerable<string>> PermissionCache;

        public GlobalCacheBootLoader(IDistributedCache<IEnumerable<string>> permissionCache)
        {
            PermissionCache = permissionCache;
        }

        /// <summary>
        /// 加载资源权限缓存
        /// <para>
        /// 只运行一次,只在应用启动时执行
        /// </para>
        /// </summary>
        public async Task LoadPermissionCacheByResourcesAsync()
        {
            var service = App.GetService<PermissionAppService>();
            var result = await service?.GetResourceAssignListAsync();

            //// TODO: 缓存需按现有租户进行加载,当前租户id为null
            //var items = service.GetOptions(PermissionType.Resource);
            //var cacheValues = new List<KeyValuePair<string, IEnumerable<string>>>();
            //foreach (var item in items)
            //{
            //    var userIds = item.Roles.SelectMany(s => s.Users).Select(s => s.Id.ToString()).Distinct();
            //    cacheValues.Add(KeyValuePair.Create(string.Format(CacheKeyConsts.PermissionResource, item.Code, null), userIds));
            //}

            await PermissionCache.SetManyAsync(result);
        }

        public async Task LoadPermissionCacheByDataPreviewRulesAsync()
        {

        }
    }
}
